from django.contrib import messages
from django.shortcuts import render, redirect, HttpResponse
from app01 import models
from django import forms

from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm

def user_list(request):
    """用户管理"""
    # 提供一个用户列表页面，并对用户数据进行分页处理

    # 从数据库中获取用户列表
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    queryset = models.UserInfo.objects.filter(org_id=current_admin_org_id)  # 获取了UserInfo的所有实例

    # 分页操作
    page_object = Pagination(request, queryset,page_size = 5)

    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, 'user_list.html', context)

def user_add(request):
    """ 添加用户（原始方式） """

    if request.method == "GET":
        current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.filter(org_id=current_admin_org_id),
        }
        return render(request, 'user_add.html', context)
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    # print("current_admin_org_id:", current_admin_org_id)
    # 获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')

    errors = {}

    if not user:
        errors['user'] = "姓名是必填字段，请填写！"
    if not pwd:
        errors['pwd'] = "密码是必填字段，请填写！"
    if not age:
        errors['age'] = "年龄是必填字段，请填写！"
    if not account:
        errors['account'] = "余额是必填字段，请填写！"
    if not ctime:
        errors['ctime'] = "入职时间是必填字段，请填写！"
    if not gender:
        errors['gender'] = "性别是必填字段，请填写！"
    if not depart_id:
        errors['depart_id'] = "部门是必填字段，请填写！"

    if errors:
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all(),
            'errors': errors
        }
        return render(request, 'user_add.html', context)


    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender, depart_id=depart_id,
                                   org_id=current_admin_org_id)

    # 返回到用户列表页面
    return redirect("/user/list/")


# def user_model_form_add(request):
#     """ 添加用户（ModelForm版本）"""
#     if request.method == "GET":
#         form = UserModelForm()
#         return render(request, 'user_model_form_add.html', {"form": form})
#
#     # 用户POST提交数据，数据校验。
#     form = UserModelForm(data=request.POST)
#     if form.is_valid():
#         # 如果数据合法，保存到数据库
#         # {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
#         # print(form.cleaned_data)
#         # models.UserInfo.objects.create(..)
#         form.save()
#         return redirect('/user/list/')
#
#     # 校验失败（在页面上显示错误信息）
#     return render(request, 'user_model_form_add.html', {"form": form})

def user_edit(request, nid):
    """ 编辑用户 """
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    row_object = models.UserInfo.objects.filter(id=nid,org_id=current_admin_org_id).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserModelForm(instance=row_object,request=request)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object,request=request)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要在用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.instance.org_id = current_admin_org_id
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    """"删除用户"""
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    models.UserInfo.objects.filter(id=nid,org_id=current_admin_org_id).delete()
    return redirect('/user/list/')
